package test.mapper;

import JDBC.DBUtil;
import test.VO.Article;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ArticleMapper {
    public int insertArticle(Article article) {
        try (
                Connection connection = DBUtil.getConnection();
        ) {
            String sql = "INSERT INTO article(title,content) " +
                    "VALUE (?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, article.getTitle());
            ps.setString(2, article.getContent());

            int num = ps.executeUpdate();

            return num;

        } catch (SQLException e) {
            e.printStackTrace();
        }
        //增
        return 0;
    }

    public int deleteArticleById(int id) {
        try (Connection connection = DBUtil.getConnection();) {
            String sql = "DELETE FROM article WHERE id=?";

            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, id);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //删、根据给定的id删除表中对应数据
        return 0;
    }


    public Article findById(int id) {
        try (Connection connection = DBUtil.getConnection();){
            String sql = "SELECT title,content " +
                    "FROM article " +
                    "WHERE id = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1,id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String title = rs.getString("title");
                String content = rs.getString("content");
                Article article = new Article();
                article.setTitle(title);
                article.setContent(content);
                return article;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Article> findAll() {
        List<Article> articleList = new ArrayList<>();

        try(Connection connection = DBUtil.getConnection();) {

            Statement statement = connection.createStatement();
            String sql = "SELECT title,content FROM article";

            ResultSet rs  = statement.executeQuery(sql);
            while (rs.next()){
                String title = rs.getString("title");
                String content = rs.getString("content");
                Article article = new Article();
                article.setTitle(title);
                article.setContent(content);
                articleList.add(article);
            }



        } catch (SQLException e) {
            e.printStackTrace();
        }
        //查所有、将表中每条记录用一个表、表示并存入集合将集合返回
        return articleList;
    }
}
